﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Web;

namespace WebFramework
{
    public class ListSegment<T> : IList<T>
    {
        private IList<T> list;
        private int start, stop;

        public ListSegment(IList<T> list, int start, int stop)
        {
            this.list = list;
            this.start = start;
            this.stop = stop;
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (int i = start; i < stop; ++i)
                yield return list[i];
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        public void Add(T item)
        {
            throw new NotSupportedException();
        }

        public void Clear()
        {
            throw new NotSupportedException();
        }

        public bool Contains(T item)
        {
            for (int i = start; i < stop; ++i)
                if (list[i].Equals(item))
                    return true;
            return false;
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            Contract.Requires(array != null);
            Contract.Requires(arrayIndex >= 0);
            Contract.Requires(array.Length >= arrayIndex + Count);

            for (int i = arrayIndex, j = start; j < stop; ++i, ++j)
                array[i] = list[j];
        }

        public bool Remove(T item)
        {
            throw new NotSupportedException();
        }

        public int Count { get { return stop - start; } }
        public bool IsReadOnly { get { return true; } }

        public int IndexOf(T item)
        {
            for (int i = start; i < stop; ++i)
                if (list[i].Equals(item))
                    return i - start;
            return -1;
        }

        public void Insert(int index, T item)
        {
            throw new NotSupportedException();
        }

        public void RemoveAt(int index)
        {
            throw new NotSupportedException();
        }

        public T this[int index]
        {
            get { return list[index - start]; }
            set { throw new NotSupportedException(); }
        }
    }
}